/**
 * n8n 完整 API 工具集
 * 提供完整的 n8n 操作能力，让 Agent 能够完全代替用户操作 n8n
 */

import type { ToolPackage } from '../../core/tool-registry.js';
import { createTool, field } from '../../core/tool-schema.js';
import { createErrorLogContext, logger } from '../../utils/logger.js';
import { N8NClient } from './client.js';
import { enhancedWorkflowTools } from './enhanced-workflow-tools.js';
import { N8NError } from './errors.js';

export { N8NClient } from './client.js';

// 创建客户端实例
const client = new N8NClient();

/**
 * 通用的MCP工具错误处理包装器
 * 确保所有N8N API错误都能被正确处理并反映在MCP响应中
 */
async function withErrorHandling<T>(
  operation: string,
  apiCall: () => Promise<T>
): Promise<{
  success: boolean;
  error?: string;
  errorType?: string;
  statusCode?: number;
  data?: T;
  message?: string;
}> {
  try {
    const result = await apiCall();
    return {
      success: true,
      data: result,
    };
  } catch (error) {
    if (error instanceof N8NError) {
      logger.error(`n8n Tools: ${operation} failed`, error.toLogContext());
      return {
        success: false,
        error: error.getUserMessage(),
        errorType: error.type,
        statusCode: error.statusCode,
      };
    }

    logger.error(`n8n Tools: ${operation} failed`, createErrorLogContext(error));
    // 对于非N8NError，直接抛出让测试失败
    throw error;
  }
}

// ========== 工作流管理工具 ==========

const listWorkflows = createTool()
  .name('n8n_list_workflows')
  .title('列出所有工作流')
  .description('获取 n8n 中所有工作流的列表，包括名称、ID、激活状态等信息')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n工作流')
  .tags(['n8n', 'workflow', 'list'])
  .build(async (params = {}) => {
    return await withErrorHandling('List workflows', () => client.getWorkflows());
  });

const getWorkflow = createTool()
  .name('n8n_get_workflow')
  .title('获取工作流详情')
  .description('获取指定工作流的完整配置，包括节点、连接、设置等')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n工作流')
  .tags(['n8n', 'workflow', 'get'])
  .parameter(
    'workflowId',
    field.required(
      field.string({
        description: '工作流ID',
      })
    )
  )
  .build(async params => {
    return await withErrorHandling('Get workflow', () => client.getWorkflow(params.workflowId));
  });

const createWorkflow = createTool()
  .name('n8n_create_workflow')
  .title('创建新工作流')
  .description('创建一个新的 n8n 工作流，可以指定名称、节点、连接等配置')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n工作流')
  .tags(['n8n', 'workflow', 'create'])
  .parameter(
    'name',
    field.required(
      field.string({
        description: '工作流名称',
      })
    )
  )
  .parameter('nodes', field.optional(field.array(field.object({}, { description: '节点配置' }))))
  .parameter(
    'connections',
    field.optional(
      field.object(
        {},
        {
          description: '节点连接配置',
        }
      )
    )
  )
  .parameter(
    'settings',
    field.optional(
      field.object(
        {},
        {
          description: '工作流设置',
        }
      )
    )
  )
  .parameter('tags', field.optional(field.array(field.string({ description: '标签' }))))
  .build(async params => {
    const result = await withErrorHandling('Create workflow', async () => {
      const workflow = await client.createWorkflow({
        name: params.name,
        nodes: params.nodes || [],
        connections: params.connections || {},
        settings: params.settings || {},
        tags: params.tags,
      });
      return {
        workflow,
        message: `工作流 "${workflow.name}" 创建成功`,
      };
    });

    if (result.success && result.data) {
      return {
        success: true,
        message: result.data.message,
        data: result.data.workflow,
      };
    }

    return result;
  });

const updateWorkflow = createTool()
  .name('n8n_update_workflow')
  .title('更新工作流')
  .description(
    '对现有工作流进行局部更新（Patch操作）。只需提供要修改的字段。\\n\\n**⚠️ 重要提示**: \\n- 当修改 `nodes` 数组时，必须提供该节点的完整结构（推荐使用 n8n_get_workflow 先获取完整结构）\\n- 对于精细的节点操作，建议使用：n8n_add_node、n8n_update_node、n8n_remove_node 等专用工具\\n- 对于节点连接，建议使用：n8n_connect_nodes、n8n_disconnect_nodes\\n- 对于损坏的工作流，建议使用：n8n_rebuild_workflow_from_template'
  )
  .version('1.3.0') // 版本升级
  .author('Test Case Writer Team')
  .category('n8n工作流')
  .tags(['n8n', 'workflow', 'update', 'patch', 'legacy'])
  .parameter(
    'workflowId',
    field.required(
      field.string({
        description: '要更新的目标工作流ID',
      })
    )
  )
  .parameter(
    'name',
    field.optional(
      field.string({
        description: '设置新的工作流名称',
      })
    )
  )
  .parameter(
    'nodes',
    field.optional(
      field.array(
        field.object(
          {},
          {
            description:
              '要更新的节点对象数组。\\n**注意**: 数组中的每个节点对象都必须是完整的结构，包含 id, name, type, typeVersion, position, parameters 等所有必需字段。推荐先用 get_workflow 获取节点当前完整的结构，再进行修改。',
          }
        )
      )
    )
  )
  .parameter(
    'connections',
    field.optional(
      field.object(
        {},
        {
          description: '节点连接配置',
        }
      )
    )
  )
  .parameter(
    'settings',
    field.optional(
      field.object(
        {},
        {
          description: '工作流设置',
        }
      )
    )
  )
  .build(async params => {
    const { workflowId, ...updateData } = params;

    try {
      // 始终先获取当前工作流的完整数据
      const currentWorkflow = await client.getWorkflow(workflowId);

      // 合并更新数据：用户提供的数据覆盖当前数据，未提供的保持原值
      // 这是一个真正的 patch 操作
      const mergedData = {
        // 必需字段：始终包含，优先使用用户提供的值
        name: updateData.name ?? currentWorkflow.name,
        nodes: updateData.nodes ?? currentWorkflow.nodes,
        connections: updateData.connections ?? currentWorkflow.connections,
        settings: updateData.settings ?? currentWorkflow.settings,

        // 可选字段（目前 n8n API 不支持通过 PUT 更新 tags 和 active）

        // 保留其他可能存在的字段
        staticData: currentWorkflow.staticData,
        createdAt: currentWorkflow.createdAt,
        updatedAt: currentWorkflow.updatedAt,
      };

      // 执行更新
      const workflow = await client.updateWorkflow(workflowId, mergedData);

      // 构建返回消息，说明哪些字段被更新了
      const updatedFields = [];
      if (updateData.name !== undefined) updatedFields.push('名称');
      if (updateData.nodes !== undefined) updatedFields.push('节点');
      if (updateData.connections !== undefined) updatedFields.push('连接');
      if (updateData.settings !== undefined) updatedFields.push('设置');

      const message =
        updatedFields.length > 0
          ? `工作流更新成功，已更新字段：${updatedFields.join('、')}`
          : '工作流更新成功（未修改任何字段）';

      return {
        success: true,
        message,
        data: workflow,
      };
    } catch (error) {
      logger.error(
        'n8n Tools: Failed to update workflow',
        createErrorLogContext(error, {
          workflowId,
          updateData,
        })
      );
      throw new Error(`更新工作流失败: ${(error as Error).message}`);
    }
  });

const deleteWorkflow = createTool()
  .name('n8n_delete_workflow')
  .title('删除工作流')
  .description('永久删除指定的工作流')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n工作流')
  .tags(['n8n', 'workflow', 'delete'])
  .parameter(
    'workflowId',
    field.required(
      field.string({
        description: '工作流ID',
      })
    )
  )
  .build(async params => {
    await client.deleteWorkflow(params.workflowId);
    return {
      success: true,
      message: `工作流已删除`,
    };
  });

const activateWorkflow = createTool()
  .name('n8n_activate_workflow')
  .title('激活工作流')
  .description('激活工作流以启用自动执行')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n工作流')
  .tags(['n8n', 'workflow', 'activate'])
  .parameter(
    'workflowId',
    field.required(
      field.string({
        description: '工作流ID',
      })
    )
  )
  .build(async params => {
    const result = await withErrorHandling('Activate workflow', async () => {
      await client.activateWorkflow(params.workflowId);
      return { message: '工作流已激活' };
    });

    if (result.success && result.data) {
      return {
        success: true,
        message: result.data.message,
      };
    }

    return result;
  });

const deactivateWorkflow = createTool()
  .name('n8n_deactivate_workflow')
  .title('停用工作流')
  .description('停用工作流以禁用自动执行')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n工作流')
  .tags(['n8n', 'workflow', 'deactivate'])
  .parameter(
    'workflowId',
    field.required(
      field.string({
        description: '工作流ID',
      })
    )
  )
  .build(async params => {
    const result = await withErrorHandling('Deactivate workflow', async () => {
      await client.deactivateWorkflow(params.workflowId);
      return { message: '工作流已停用' };
    });

    if (result.success && result.data) {
      return {
        success: true,
        message: result.data.message,
      };
    }

    return result;
  });

// ========== 执行管理工具 ==========

const executeWorkflow = createTool()
  .name('n8n_execute_workflow')
  .title('执行工作流')
  .description('手动触发工作流执行，可以传入测试数据')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n执行')
  .tags(['n8n', 'execution', 'run'])
  .parameter(
    'workflowId',
    field.required(
      field.string({
        description: '工作流ID',
      })
    )
  )
  .parameter(
    'data',
    field.optional(
      field.object(
        {},
        {
          description: '执行时传入的数据',
        }
      )
    )
  )
  .build(async params => {
    const result = await client.executeWorkflow(params.workflowId, params.data);
    return {
      success: true,
      message: '工作流执行成功',
      data: result,
    };
  });

const getExecutions = createTool()
  .name('n8n_get_executions')
  .title('获取执行历史')
  .description('获取工作流的执行历史记录')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n执行')
  .tags(['n8n', 'execution', 'history'])
  .parameter(
    'workflowId',
    field.optional(
      field.string({
        description: '工作流ID（可选，不指定则获取所有）',
      })
    )
  )
  .parameter(
    'limit',
    field.optional(
      field.number({
        description: '返回记录数量限制（默认20）',
      })
    )
  )
  .build(async params => {
    const result = await client.getExecutions(params.workflowId, params.limit || 20);
    return {
      success: true,
      data: result,
    };
  });

const getExecutionDetails = createTool()
  .name('n8n_get_execution_details')
  .title('获取执行详情')
  .description('获取特定执行的详细信息，包括每个节点的执行结果')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n执行')
  .tags(['n8n', 'execution', 'details'])
  .parameter(
    'executionId',
    field.required(
      field.string({
        description: '执行ID',
      })
    )
  )
  .build(async params => {
    const result = await client.getExecution(params.executionId);
    return {
      success: true,
      data: result,
    };
  });

const retryExecution = createTool()
  .name('n8n_retry_execution')
  .title('重试执行')
  .description('重试失败的工作流执行')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n执行')
  .tags(['n8n', 'execution', 'retry'])
  .parameter(
    'executionId',
    field.required(
      field.string({
        description: '执行ID',
      })
    )
  )
  .build(async params => {
    const result = await client.retryExecution(params.executionId);
    return {
      success: true,
      message: '执行重试成功',
      data: result,
    };
  });

const stopExecution = createTool()
  .name('n8n_stop_execution')
  .title('停止执行')
  .description('停止正在运行的工作流执行')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n执行')
  .tags(['n8n', 'execution', 'stop'])
  .parameter(
    'executionId',
    field.required(
      field.string({
        description: '执行ID',
      })
    )
  )
  .build(async params => {
    await client.stopExecution(params.executionId);
    return {
      success: true,
      message: '执行已停止',
    };
  });

const deleteExecution = createTool()
  .name('n8n_delete_execution')
  .title('删除执行记录')
  .description('删除工作流的执行记录')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n执行')
  .tags(['n8n', 'execution', 'delete'])
  .parameter(
    'executionId',
    field.required(
      field.string({
        description: '执行ID',
      })
    )
  )
  .build(async params => {
    await client.deleteExecution(params.executionId);
    return {
      success: true,
      message: '执行记录已删除',
    };
  });

// ========== 凭据管理工具 ==========

const listCredentials = createTool()
  .name('n8n_list_credentials')
  .title('列出所有凭据')
  .description('获取 n8n 中所有凭据的列表')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n凭据')
  .tags(['n8n', 'credential', 'list'])
  .build(async (params = {}) => {
    return await withErrorHandling('List credentials', () => client.getCredentials());
  });

const getCredential = createTool()
  .name('n8n_get_credential')
  .title('获取凭据详情')
  .description('获取指定凭据的详细信息')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n凭据')
  .tags(['n8n', 'credential', 'get'])
  .parameter(
    'credentialId',
    field.required(
      field.string({
        description: '凭据ID',
      })
    )
  )
  .build(async params => {
    const result = await client.getCredential(params.credentialId);
    return {
      success: true,
      data: result,
    };
  });

const createCredential = createTool()
  .name('n8n_create_credential')
  .title('创建凭据')
  .description('创建新的凭据配置')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n凭据')
  .tags(['n8n', 'credential', 'create'])
  .parameter(
    'name',
    field.required(
      field.string({
        description: '凭据名称',
      })
    )
  )
  .parameter(
    'type',
    field.required(
      field.string({
        description: '凭据类型',
      })
    )
  )
  .parameter(
    'data',
    field.optional(
      field.object(
        {},
        {
          description: '凭据数据',
        }
      )
    )
  )
  .build(async params => {
    const result = await client.createCredential({
      name: params.name,
      type: params.type,
      ...params.data,
    });
    return {
      success: true,
      message: '凭据创建成功',
      data: result,
    };
  });

const deleteCredential = createTool()
  .name('n8n_delete_credential')
  .title('删除凭据')
  .description('删除指定的凭据配置')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n凭据')
  .tags(['n8n', 'credential', 'delete'])
  .parameter(
    'credentialId',
    field.required(
      field.string({
        description: '凭据ID',
      })
    )
  )
  .build(async params => {
    await client.deleteCredential(params.credentialId);
    return {
      success: true,
      message: '凭据已删除',
    };
  });

// ========== 节点类型工具 ==========

const searchNodes = createTool()
  .name('n8n_search_nodes')
  .title('搜索 n8n 节点')
  .description(
    '根据关键词搜索 n8n 节点，支持按类别、分组和推荐值过滤。当不知道用什么关键词时，建议设置 minRecommendValue >= 6 获取推荐节点'
  )
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n节点')
  .tags(['n8n', 'node', 'search'])
  .parameter(
    'query',
    field.optional(
      field.string({
        description:
          '搜索关键词，可以是节点名称、描述或功能相关的关键词。如果不提供，建议设置 minRecommendValue',
      })
    )
  )
  .parameter(
    'category',
    field.optional(
      field.string({
        description: '按类别过滤，如 communication, database, cloud 等',
      })
    )
  )
  .parameter(
    'group',
    field.optional(
      field.string({
        description: '按分组过滤，如 input, output, transform 等',
      })
    )
  )
  .parameter(
    'minRecommendValue',
    field.optional(
      field.number({
        description: '最小推荐值（1-10），只显示推荐值 >= 该值的节点。建议设置 >= 8 获取推荐节点',
        min: 1,
        max: 10,
      })
    )
  )
  .parameter(
    'limit',
    field.optional(
      field.number({
        description: '限制返回结果数量，默认 20',
      })
    )
  )
  .build(async params => {
    try {
      const { n8nNodeDb } = await import('../../services/n8n-node-db.js');

      const result = await n8nNodeDb.searchNodes({
        query: params.query,
        category: params.category,
        group: params.group,
        minRecommendValue: params.minRecommendValue,
        limit: params.limit || 20,
      });

      // 构建描述性消息
      const filterDescriptions: string[] = [];
      if (params.query) filterDescriptions.push(`关键词: "${params.query}"`);
      if (params.category) filterDescriptions.push(`类别: ${params.category}`);
      if (params.group) filterDescriptions.push(`分组: ${params.group}`);
      if (params.minRecommendValue)
        filterDescriptions.push(`推荐值 >= ${params.minRecommendValue}`);

      const filterText =
        filterDescriptions.length > 0 ? ` (过滤条件: ${filterDescriptions.join(', ')})` : '';

      return {
        success: true,
        data: result.nodes.map(node => ({
          ...node,
          recommendValue: node.recommendValue, // 确保返回推荐值
        })),
        total: result.total,
        message: `找到 ${result.total} 个匹配的节点${filterText} (显示前 ${result.nodes.length} 个)`,
        filters: {
          query: params.query || null,
          category: params.category || null,
          group: params.group || null,
          minRecommendValue: params.minRecommendValue || null,
        },
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error occurred',
      };
    }
  });

const getNodeDetails = createTool()
  .name('n8n_get_node_details')
  .title('获取节点详细信息')
  .description('获取特定节点的完整配置信息，包括属性定义、输入输出等详细配置')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n节点')
  .tags(['n8n', 'node', 'details'])
  .parameter(
    'nodeName',
    field.required(
      field.string({
        description: '节点名称，如 HttpRequest, Webhook 等',
      })
    )
  )
  .build(async params => {
    try {
      const { n8nNodeDb } = await import('../../services/n8n-node-db.js');

      const nodeDetails = await n8nNodeDb.getNodeDetails(params.nodeName);

      if (!nodeDetails) {
        return {
          success: false,
          error: `未找到节点 "${params.nodeName}"，请检查节点名称是否正确或先使用 n8n_search_nodes 搜索`,
        };
      }

      return {
        success: true,
        data: {
          name: nodeDetails.name,
          displayName: nodeDetails.displayName,
          description: nodeDetails.description,
          version: nodeDetails.version,
          group: nodeDetails.group,
          category: nodeDetails.category,
          subtitle: nodeDetails.subtitle,
          fullConfig: nodeDetails.fullConfig,
        },
        message: `获取节点 "${nodeDetails.displayName}" 详细信息成功`,
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error occurred',
      };
    }
  });

// ========== 标签管理工具 ==========

const listTags = createTool()
  .name('n8n_list_tags')
  .title('列出所有标签')
  .description('获取 n8n 中所有标签')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n标签')
  .tags(['n8n', 'tag', 'list'])
  .build(async (params = {}) => {
    try {
      const result = await client.getTags();
      return {
        success: true,
        data: result,
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error occurred',
      };
    }
  });

const createTag = createTool()
  .name('n8n_create_tag')
  .title('创建标签')
  .description('创建新的标签')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n标签')
  .tags(['n8n', 'tag', 'create'])
  .parameter(
    'name',
    field.required(
      field.string({
        description: '标签名称',
      })
    )
  )
  .build(async params => {
    const result = await client.createTag({ name: params.name });
    return {
      success: true,
      message: '标签创建成功',
      data: result,
    };
  });

const deleteTag = createTool()
  .name('n8n_delete_tag')
  .title('删除标签')
  .description('删除指定的标签')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n标签')
  .tags(['n8n', 'tag', 'delete'])
  .parameter(
    'tagId',
    field.required(
      field.string({
        description: '标签ID',
      })
    )
  )
  .build(async params => {
    await client.deleteTag(params.tagId);
    return {
      success: true,
      message: '标签已删除',
    };
  });

// ========== 系统管理工具 ==========

const getSystemInfo = createTool()
  .name('n8n_system_info')
  .title('获取系统信息')
  .description('获取 n8n 系统信息')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n系统')
  .tags(['n8n', 'system', 'info'])
  .build(async (params = {}) => {
    try {
      const result = await client.getSystemInfo();
      return {
        success: true,
        data: result,
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error occurred',
      };
    }
  });

const getSystemHealth = createTool()
  .name('n8n_system_health')
  .title('获取系统健康状态')
  .description('获取 n8n 系统健康状态')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n系统')
  .tags(['n8n', 'system', 'health'])
  .build(async (params = {}) => {
    try {
      const result = await client.getSystemHealth();
      return {
        success: true,
        data: result,
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error occurred',
      };
    }
  });

// ========== 工作流分享工具 ==========

const shareWorkflow = createTool()
  .name('n8n_share_workflow')
  .title('分享工作流')
  .description('生成工作流的分享链接')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n工作流')
  .tags(['n8n', 'workflow', 'share'])
  .parameter(
    'workflowId',
    field.required(
      field.string({
        description: '工作流ID',
      })
    )
  )
  .build(async params => {
    const result = await client.shareWorkflow(params.workflowId);
    return {
      success: true,
      message: '工作流已分享',
      data: result,
    };
  });

// ========== Webhook 管理工具 ==========

const getWorkflowWebhooks = createTool()
  .name('n8n_get_workflow_webhooks')
  .title('获取工作流 Webhooks')
  .description('获取指定工作流中所有 Webhook 节点的信息和 URL')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n Webhook')
  .tags(['n8n', 'webhook', 'list'])
  .parameter(
    'workflowId',
    field.required(
      field.string({
        description: '工作流ID',
      })
    )
  )
  .build(async params => {
    const webhooks = await client.getWorkflowWebhooks(params.workflowId);
    return {
      success: true,
      data: webhooks,
      message: `找到 ${webhooks.length} 个 Webhook 节点`,
    };
  });

const getAllActiveWebhooks = createTool()
  .name('n8n_get_all_active_webhooks')
  .title('获取所有活动 Webhooks')
  .description('获取所有激活工作流中的 Webhook 信息')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n Webhook')
  .tags(['n8n', 'webhook', 'active'])
  .build(async (params = {}) => {
    try {
      const results = await client.getAllActiveWebhooks();
      const totalWebhooks = results.reduce((sum, r) => sum + r.webhooks.length, 0);
      return {
        success: true,
        data: results,
        message: `找到 ${results.length} 个工作流共 ${totalWebhooks} 个 Webhook`,
      };
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error occurred',
      };
    }
  });

const createWebhookWorkflow = createTool()
  .name('n8n_create_webhook_workflow')
  .title('创建 Webhook 工作流')
  .description('创建一个带有 Webhook 触发器的新工作流')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n Webhook')
  .tags(['n8n', 'webhook', 'create'])
  .parameter(
    'name',
    field.required(
      field.string({
        description: '工作流名称',
      })
    )
  )
  .parameter(
    'webhookPath',
    field.required(
      field.string({
        description: 'Webhook 路径（例如：my-webhook）',
      })
    )
  )
  .parameter(
    'httpMethod',
    field.optional(
      field.string({
        description: 'HTTP 方法（默认 POST）',
      })
    )
  )
  .parameter(
    'responseMode',
    field.optional(
      field.string({
        description: '响应模式：onReceived（立即响应）或 lastNode（最后节点响应）',
      })
    )
  )
  .build(async params => {
    const workflow = await client.createWorkflowWithWebhook(
      params.name,
      params.webhookPath,
      params.httpMethod || 'POST',
      (params.responseMode as any) || 'onReceived'
    );

    // 获取 webhook URL
    const webhooks = await client.getWorkflowWebhooks(workflow.id);

    return {
      success: true,
      message: `Webhook 工作流 "${workflow.name}" 创建成功`,
      data: {
        workflow,
        webhooks,
      },
    };
  });

const testWebhook = createTool()
  .name('n8n_test_webhook')
  .title('测试 Webhook')
  .description('向指定的 Webhook URL 发送测试请求')
  .version('1.0.0')
  .author('Test Case Writer Team')
  .category('n8n Webhook')
  .tags(['n8n', 'webhook', 'test'])
  .parameter(
    'webhookUrl',
    field.required(
      field.string({
        description: 'Webhook URL',
      })
    )
  )
  .parameter(
    'data',
    field.optional(
      field.object(
        {},
        {
          description: '要发送的数据',
        }
      )
    )
  )
  .parameter(
    'method',
    field.optional(
      field.string({
        description: 'HTTP 方法（默认 POST）',
      })
    )
  )
  .parameter(
    'headers',
    field.optional(
      field.object(
        {},
        {
          description: '自定义 HTTP 头',
        }
      )
    )
  )
  .build(async params => {
    try {
      const result = await client.testWebhook(
        params.webhookUrl,
        params.data,
        params.method || 'POST',
        params.headers || {}
      );

      return {
        success: true,
        message: 'Webhook 测试成功',
        data: result,
      };
    } catch (error) {
      return {
        success: false,
        error: (error as Error).message,
        message: 'Webhook 测试失败',
      };
    }
  });

// ========== 工具导出 ==========

export const tools = [
  // 工作流管理
  listWorkflows,
  getWorkflow,
  createWorkflow,
  updateWorkflow, // 保留原有方法作为兼容性选项
  deleteWorkflow,
  activateWorkflow,
  deactivateWorkflow,
  // shareWorkflow,

  // 增强工作流操作（推荐使用）
  ...enhancedWorkflowTools.tools,

  // 执行管理
  executeWorkflow,
  getExecutions,
  getExecutionDetails,
  // retryExecution,
  stopExecution,
  // deleteExecution,

  // 凭据管理
  listCredentials,
  getCredential,
  createCredential,
  // deleteCredential,

  // 节点搜索和详情
  searchNodes,
  getNodeDetails,

  // 标签管理
  listTags,
  createTag,
  deleteTag,

  // Webhook 管理
  getWorkflowWebhooks,
  getAllActiveWebhooks,
  createWebhookWorkflow,
  testWebhook,

  // 系统管理
  getSystemInfo,
  getSystemHealth,
];

// 导出元数据
export const meta = {
  name: 'n8n',
  version: '2.1.0',
  description:
    'n8n 完整 API 工具集，提供工作流开发、执行、运维等全方位管理能力。现已包含增强节点操作工具，显著降低更新工作流时的出错几率。',
  author: 'Test Case Writer Team',
};

// 默认导出
const toolPackage: ToolPackage = {
  tools,
  meta,
};

export default toolPackage;
